<template>
	<view @tap="toggle" class="m-switch" :class="{'m-switch-disabled':disabled}" :style="[switchStyle]">
		<view class="m-switch-circle" :style="[circleStyle]"></view>
	</view>
</template>

<script>
	export default {
		name: 'm-switch',
		props: {
			value: {
				type: Number | String | Boolean,
				default: '1'
			},
			activeColor: {
				type: String,
				default: ''
			},
			inactiveColor: {
				type: String,
				default: '#fff'
			},
			size: {
				type: String,
				default: '50rpx'
			},
			disabled: {
				type: Boolean,
				default: false
			},
		},
		computed: {
			switchStyle() {
				return {
					width: `${this.$m.getSizeUnitValue(this.size)*2}rpx`,
					height: this.size,
					borderRadius: this.size,
					backgroundColor: !!Number(this.value) ? this.activeColor : this.inactiveColor
				}
			},
			circleStyle() {
				return {
					width: this.size,
					height: this.size,
					transform: !!Number(this.value) ? `translateX(${this.size})` : `translateX(0)`
				}
			},
		},
		methods: {
			toggle() {
				if (this.disabled) return
				let value = !this.value
				switch (typeof(this.value)) {
					case 'string':
						value = this.value === '1' ? '0' : '1'
						break;
					case 'number':
						value = Number(!!!this.value)
						break;
					default:
						break;
				}
				this.$emit('input', value)
				this.$emit('change', value)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.m-switch {
		position: relative;
		border-width: 1px;
		border-color: rgba(0, 0, 0, 0.1);
		border-style: solid;
		transition: background-color 0.3s;
		box-sizing: content-box;
		background-color: $uni-color-primary;
	}

	.m-switch-disabled {
		opacity: 0.3;
	}

	.m-switch-circle {
		position: absolute;
		left: 0;
		top: 0;
		background-color: #fff;
		border-radius: 50%;
		box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05), 0 2px 2px 0 rgba(0, 0, 0, 0.1), 0 3px 3px 0 rgba(0, 0, 0, 0.05);
		transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
	}
</style>
